from topo import topo

class hosts:
    def __init__(self):
        self.quantity = 0
        self.topo = topo()
        self.v2h = {}
        self.h2v = {}
        self.h2slot = {}
    def load(self, hostf, topof):
        hfile = open(hostf, 'r')
        hostlines = hfile.readlines()
        for hostline in hostlines:
            tricell = hostline.split()
            if len(tricell) == 1:
                self.quantity = int(tricell[0])
            if len(tricell) == 2:
                self.h2slot[int(tricell[0])] = int(tricell[1])
                self.h2v[int(tricell[0])] = []
        hfile.close()
        self.topo.load(topof)
        self.topo.floyd_warshall()
    def place(self, vm, host):
        if self.v2h.has_key(vm):
            #print str(vm) + ' has been placed elsewhere'
            return False
        if len(self.h2v[host]) >= self.h2slot[host]:
            #print str(host) + ' has no more place for ' + str(vm)
            return False
        self.h2v[host].append(vm)
        self.v2h[vm] = host
        #print self.v2h
    def remove(self, vm, host):
        if self.v2h[vm] == host:
            self.v2h.pop(vm)
            self.h2v[host].remove(vm)
            return True
        else:
            return False
    def clear(self):
        self.v2h.clear()
        for key in self.h2v.keys():
            self.h2v[key] = []
    def distance(self, i, j):
        #print i, j
        #print self.v2h[i], self.v2h[j]
        if i == j:
            return 0
        if self.v2h[i] == self.v2h[j]:
            return 0
        return self.topo.distance[self.v2h[i]][self.v2h[j]]
#hentity = hosts()
#hentity.load('../host.in', '../topo.in')
#print hentity.topo.distance
        
